<?php
namespace control;

/*
*序时账
*/

class sequentialAccountClass extends adIndexClass
{
    private const page = 'sequentialAccount';
    private const table = 'voucher';
    private const tableMx = 'voucher_detail';
    private const title = '序时账';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        $tr = [
            'recordDate'          => [
                'name'  => "日期",
                'width' => 200,
                'sort' => 1,
            ],
            'voucherNo'  => [
                'name'  => '凭证号',
                'width' => 200,
            ],
            'summary'         => [
                'name'  => '摘要',
                'width' => 200,
            ],
            'code'          => [
                'name'  => '科目编码',
                'width' => 200,
            ],
            'name'          => [
                'name'  => '科目名称',
                'width' => 200,
            ],
            'voucherNum'          => [
                'name'  => '数量',
                'width' => 200,
                'sort' => 1,
            ],
            'jie'          => [
                'name'  => '借方',
                'width' => 150,
                'sort' => 1,
            ],
            'dai'          => [
                'name'  => '贷方',
                'width' => 150,
            ]
        ];
        switch ($fun) {
            case 'column':
                $tr = array_merge($tr,
                    [
                        'kehuOrderNo'          => [
                            'name'  => "客户编码",
                            'width' => 150,
                        ],
                        'companyName'  => [
                            'name'  => '客户名称',
                            'width' => 150,
                        ],
                        'supplierCode'         => [
                            'name'  => '供应商编码',
                            'width' => 150,
                        ],
                        'supplierName'          => [
                            'name'  => '供应商名称',
                            'width' => 150,
                        ],
                        'staffOrderNo'          => [
                            'name'  => '员工编码',
                            'width' => 150,
                        ],
                        'staffName'          => [
                            'name'  => '员工名称',
                            'width' => 150,
                        ],
                        'departmentOrderNo'          => [
                            'name'  => '部门编码',
                            'width' => 150,
                        ],
                        'departmentName'          => [
                            'name'  => '部门名称',
                            'width' => 150,
                        ],
                        'materialCode'          => [
                            'name'  => '存货编码',
                            'width' => 150,
                        ],
                        'materialName'          => [
                            'name'  => '存货名称',
                            'width' => 150,
                        ],
                        'projectOrderNo'          => [
                            'name'  => '项目编码',
                            'width' => 150,
                        ],
                        'projectName'          => [
                            'name'  => '项目名称',
                            'width' => 150,
                        ],
                        'cashCode'          => [
                            'name'  => '现金流编码',
                            'width' => 150,
                        ],
                        'cashName'          => [
                            'name'  => '现金流名称',
                            'width' => 150,
                        ]
                    ]
                );
                break;
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $maxDate = accountDetailsClass::getMaxDate();
        $minDate = accountDetailsClass::getMinDate();
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "会计期间" => text(array("name" => "createTime", 'value' => static::rGet(self::$stid .self::$coid. 'SearchMonth') ?: date('Y-m',strtotime($maxDate)) . ' ~ ' . date('Y-m',strtotime($maxDate)),  'laydate' => ['type' => 'month','range'=>'~','min'=>"'{$minDate}'",'max'=>"'{$maxDate}'"])),
                    "凭证字"   => idSelect(array('name' => 'voucherWordId', 'sqlForm' => "voucher_word where coid = '" . self::$coid . "'", 'sqlId' => 'id', 'sqlField' => 'word')),
                    '摘要' => text(array("name" => "summary")),
                ],
                [
                    '科目'  => componentClass::customSubject(['name'=>'formSubjectId', 'title'=>'请选择'])."-\n".
                        componentClass::customSubject(['name'=>'toSubjectId', 'title'=>'请选择']),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
        $button .= "<span style='margin-left: 15px'></span>" . checkbox(['name' => 'showAsset', 'value' => [1 => '显示辅助项'], 'checked' => [static::rGet(self::page.self::$stid.'Column')?:0]]);
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        static::rSet(self::$stid .self::$coid. 'SearchMonth', $this->post('createTime'));;
        //like查询数组
        $like = array(
            "summary" => $this->post('summary'),
        );
        //全等查询数组
        $equal = array(
            'voucherWordId' => $this->post('voucherWordId'),
            "isTemplate" => '否',
            'a.coid' => self::$coid,
        );
        $and = voucherClass::joinWhere();
        $and .= self::timeComparison($this->post('createTime'),'month', 'recordDate');
        if ($this->post('formSubjectId')) {
            $subjectObj = new subjectClass();
            $subjectIdArr = $subjectObj->getFromToSubject($this->post('formSubjectId'), $this->post('toSubjectId'));
            $and .= " and b.subjectId in ('" . implode("','",$subjectIdArr) . "')";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.recordDate desc,a.voucherNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table." as a join ".self::tableMx.' as b on a.id = b.orderId',
            'field'=>"b.*,a.recordDate,a.voucherWordId,a.voucherNo",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        if (static::rGet(self::page.self::$stid.'Column')){
            $installSearch = $this->installSearch(self::page.'-column');
        }else {
            $installSearch = $this->installSearch();
        }
        // 月份选择器
        $monthSelector = componentClass::monthSelector($this->post('createTime'));
        $headCount = count($installSearch['head']);
        $installSearch['head'][$headCount-1] .= $monthSelector['button'];
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            $voucherWord = query('voucher_word',"id = '$array[voucherWordId]'");
            $subject = query('subject',"id = '$array[subjectId]'");
            $jie = $dai = '';
            if ($array['direction'] =='借'){
                $jie = self::centToYuan($array['money']);
            }else{
                $dai = self::centToYuan($array['money']);
            }
            $voucherNo = componentClass::urlTitle($voucherWord['word'] . '-' . $array['voucherNo'], root . 'control/adIndex.html?cla=voucherEdit&fun=room&id=' . $array['orderId'], '录凭证');
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'voucherNo':
                        $row[] = $voucherNo;
                        break;
                    case 'code':
                        $row[] = $subject[$key];
                        break;
                    case 'name':
                        $row[] = subjectClass::getName($subject['id']);
                        break;
                    case 'voucherNum':
                        $row[] = $array['voucherNum'] !=0?voucherEditClass::formatNum($array['voucherNum']):'';
                        break;
                    case 'jie':
                        $row[] = $jie;
                        break;
                    case 'dai':
                        $row[] = $dai;
                        break;
                    case 'kehuOrderNo':
                    case 'companyName':
                        $kehu = query('kehu',"khid = '$array[khid]'");
                        $row[] = $key=='kehuOrderNo'?$kehu['orderNo']:$kehu['companyName'];
                        break;
                    case 'supplierCode':
                    case 'supplierName':
                        $supplier = query('supplier',"id = '$array[supplierId]'");
                        $row[] = $key=='supplierCode'?$supplier['code']:$supplier['name'];
                        break;
                    case 'staffOrderNo':
                    case 'staffName':
                        $staff = query('staff',"stid = '$array[staffId]'");
                        $row[] = $key=='staffOrderNo'?$staff['orderNo']:$staff['name'];
                        break;
                    case 'departmentOrderNo':
                    case 'departmentName':
                        $department = query('department',"id = '$array[departmentId]'");
                        $row[] = $key=='departmentOrderNo'?$department['orderNo']:$department['name'];
                        break;
                    case 'materialCode':
                    case 'materialName':
                        $material = query('material',"id = '$array[materialId]'");
                        $row[] = $key=='materialCode'?$material['code']:$material['name'];
                        break;
                    case 'projectOrderNo':
                    case 'projectName':
                        $project = query('project',"id = '$array[projectId]'");
                        $row[] = $key=='projectOrderNo'?$project['orderNo']:$project['name'];
                        break;
                    case 'cashCode':
                    case 'cashName':
                        $cash = query('cash',"id = '$array[cashId]'");
                        $row[] = $key=='materialCode'?$cash['code']:$cash['name'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] =
            $page['hint'] .
            "<div class='acct-main-container'>
                <form name='listForm'>" .
                    $li .
                "</form>" .
                $monthSelector['html'].
            "</div>" .
            $this->js().
            $page['button'] .
            clear;
        return json_encode($json, 320);
    }

    public function js(){
        return <<<eof
<script>
   $("[name='showAsset[]']").on('click',function() {
       let show = 0;
       if ($(this).is(":checked")){
           show = 1;
       }
       $.post(root+'control/adIndex.html?cla=sequentialAccount&fun=showAsset',{show:show},function(res) {
          location.reload();
       },'json')
   })
</script>
eof;

    }

    public function showAsset(){
        $bool = $this->post('show');
        if ($bool){
            static::rSet(self::page.self::$stid.'Column',1);
        }else{
            static::rSet(self::page.self::$stid.'Column','');
        }

        $json['warn'] = 2;
        return json_encode($json,320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data = [];
            $sql = $_SESSION[self::page]['sql'];
            $title = array("日期", "凭证号", "摘要", "科目编码", "科目名称", "数量", "借方", "贷方");
            if (static::rGet(self::page.self::$stid.'Column')){
                $title = array_merge($title,['客户编码','客户名称','供应商编码','供应商名称','员工编码','员工名称','部门编码','部门名称','存货编码','存货名称','项目编码','项目名称','现金流编码','现金流名称']);
            }
            $result = self::sqlFind($sql);
                foreach ($result as $array) {
                    $voucherWord = query('voucher_word',"id = '$array[voucherWordId]'");
                    $subject = query('subject',"id = '$array[subjectId]'");
                    $jie = $dai = '';
                    if ($array['direction'] =='借'){
                        $jie = self::centToYuan($array['money']);
                    }else{
                        $dai = self::centToYuan($array['money']);
                    }
                    $voucherNo = $voucherWord['word'] . '-' . $array['voucherNo'];
                    $tbody = array($array['recordDate'], $voucherNo,$array['summary'], $subject['code'],subjectClass::getName($subject['id']), $array['voucherNum'] !=0?voucherEditClass::formatNum($array['voucherNum']):'', $jie,$dai);
                    if (static::rGet(self::page.self::$stid.'Column')){
                        $kehu = query('kehu',"khid = '$array[khid]'");
                        $supplier = query('supplier',"id = '$array[supplierId]'");
                        $staff = query('staff',"stid = '$array[staffId]'");
                        $department = query('department',"id = '$array[departmentId]'");
                        $project = query('project',"id = '$array[projectId]'");
                        $cash = query('cash',"id = '$array[cashId]'");
                        $material = query('material',"id = '$array[materialId]'");
                        $tbody = array_merge($tbody,[
                            $kehu['orderNo'],
                            $kehu['companyName'],
                            $supplier['code'],
                            $supplier['name'],
                            $staff['orderNo'],
                            $staff['name'],
                            $department['orderNo'],
                            $department['name'],
                            $material['code'],
                            $material['name'],
                            $project['orderNo'],
                            $project['name'],
                            $cash['code'],
                            $cash['name']
                        ]);
                    }
                    $data[] = $tbody;
                }
            $text = $this->control['name'] . "导出了".self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title.".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }
}

